package cn.edu.zut.project1.controller;


import cn.edu.zut.project1.pojo.Message;
import cn.edu.zut.project1.pojo.Result;
import cn.edu.zut.project1.pojo.User;
import cn.edu.zut.project1.service.MessageService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @PostMapping("/user/send")
    public Result sendUserMsg(
            @RequestParam Integer receiverId,  // 对方用户ID（前端传）
            @RequestParam String orderNo,     // 关联订单编号（前端传）
            @RequestParam String content,      // 消息内容（前端传）
            HttpSession session) {

        // 从Session拿当前登录用户（发送者）
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return Result.error("请先登录");
        }
        Integer senderId = loginUser.getId();

        try {
            messageService.sendUserMsg(senderId, receiverId, orderNo, content);
            return Result.success("消息发送成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    // 2. 查订单的所有消息（系统提醒+双方聊天）
    @GetMapping("/order/{orderId}")
    public Result getOrderMsgs(@PathVariable String orderNo, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            return Result.error("请先登录");
        }

        try {
            List<Message> msgs = messageService.getOrderMsgs(orderNo, loginUser.getId());
            return Result.success(msgs.toString());
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

}
